package com.ztj.demo.controller;

import com.google.common.collect.Lists;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.ztj.wood.common.system.Logs;
import com.ztj.wood.web.controller.BasicController;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

/**
 * 通用页面导出
 *
 * @Author 张宁
 * @Date 2020-06-28 10:43:00
 */
@Controller
@RequestMapping("/commonExport")
public class CommonExportController extends BasicController {
    private static Logger logger = Logs.getLogger(CommonExportController.class);

    /**
     * html转word
     *
     * @param html encodeURI的html源码
     * @return 保存的临时文件名
     * @throws Exception 异常
     */
    @PostMapping("/html2word")
    @ResponseBody
    public String html2word(String html) throws Exception {
        String fileName = "exportWord" + System.currentTimeMillis() + ".doc";
        String exportWordPath = genPathFolder("exportWord");
        html = URLDecoder.decode(html, "utf-8");
        try (FileOutputStream fos = new FileOutputStream(exportWordPath + File.separator + fileName)) {
            IOUtils.write(html, fos, "utf-8");
            fos.flush();
        }
        return fileName;
    }

    /**
     * html转换pdf
     *
     * @param html encodeURI的html源码
     * @return 保存的临时文件名
     * @throws Exception 异常
     */
    @PostMapping("/html2pdf")
    @ResponseBody
    public String html2pdf(String html) {
        String fileName = "exportPdf" + System.currentTimeMillis() + ".pdf";
        try {
            String exportPdfPath = genPathFolder("exportPdf");
            html = URLDecoder.decode(html, "utf-8");
            ConverterProperties props = new ConverterProperties();
            DefaultFontProvider defaultFontProvider = new DefaultFontProvider(false, false, false);
            String classPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath() + "com/ztj/demo/font/";
            List<String> fontsFile = Lists.newArrayList("msyh.TTC,0", "simsun.TTC,0", "arial.TTF");
            fontsFile.forEach(f -> {
                FontProgram fontProgram2 = null;
                try {
                    fontProgram2 = FontProgramFactory.createFont(classPath + f);
                } catch (IOException e) {
                    logger.error("加载字体出现错误:", e);
                    return;
                }
                defaultFontProvider.addFont(fontProgram2);
            });
            props.setFontProvider(defaultFontProvider);
            try (FileOutputStream fos = new FileOutputStream(exportPdfPath + File.separator + fileName)) {
                PdfWriter writer = new PdfWriter(fos);
                HtmlConverter.convertToPdf(html, writer, props);
                writer.close();
            }
        } catch (Exception e) {
            logger.error("导出PDF出现异常", e);
            fileName = "";
        }
        return fileName;
    }

    /**
     * html转excel
     *
     * @param html encodeURI的html源码
     * @return 保存的临时文件名
     * @throws Exception 异常
     */
    @PostMapping("/html2excel")
    @ResponseBody
    public String html2excel(String html) throws Exception {
        String fileName = "exportExcel" + System.currentTimeMillis() + ".xls";
        String exportWordPath = genPathFolder("exportExcel");
        html = URLDecoder.decode(html, "utf-8");
        try (FileOutputStream fos = new FileOutputStream(exportWordPath + File.separator + fileName)) {
            IOUtils.write(html, fos, "utf-8");
            fos.flush();
        }
        return fileName;
    }

    /**
     * 下载并删除文件
     *
     * @param data             文件名
     * @param downloadFileName 下载文件名
     * @param response         res
     * @throws Exception 可能出现的异常
     */
    @GetMapping("/downLoadFile")
    public void downLoadFile(String data, String downloadFileName, HttpServletResponse response) throws Exception {
        File file = new File(this.getClass().getResource("/").getFile());
        String webFloder = file.getParentFile().getParentFile().getAbsolutePath();
        String workFloder = "exportWord";
        if (StringUtils.endsWith(downloadFileName, ".pdf")) {
            workFloder = "exportPdf";
        } else if (StringUtils.endsWith(downloadFileName, ".xls")) {
            workFloder = "exportExcel";
        }
        String exportWordPath = webFloder + File.separator + workFloder;
        response.setContentType("application/octet-stream");//设置文件类型
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(downloadFileName, "UTF-8"));
        File oldFile = new File(exportWordPath + File.separator + data);
        if (oldFile.exists()) {
            try (FileInputStream in = new FileInputStream(oldFile)) {
                IOUtils.copy(in, response.getOutputStream());
            }
            oldFile.delete();
        }
    }

    /**
     * 根据资源文件夹名称获取路径
     *
     * @param floderName 保存文件夹名称
     * @return 保存文件的路径
     */
    public String genPathFolder(String floderName) {
        File file = new File(this.getClass().getResource("/").getFile());
        String webFloder = file.getParentFile().getParentFile().getAbsolutePath();
        String exportPath = webFloder + File.separator + floderName;
        File exportWordFloder = new File(exportPath);
        if (!exportWordFloder.exists()) {
            exportWordFloder.mkdir();
        }
        return exportPath;
    }
}
